﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
using Red.Core;
using Red.Core.Extensions;

namespace Red.Controls.Tile
{
    public class Reserve
    {
        #region Private Data

        FrameworkElement _parent;

        #endregion Private Data

        #region Public Properties

        public ObservableCollection<Tile> Tiles { get; private set; } = new ObservableCollection<Tile>();

        public Callback Callback { get; internal set; }

        public Utils.DragDrop DragDrop { get; private set; } = new Utils.DragDrop();

        #endregion Public Properties

        #region C-Tor

        public Reserve( FrameworkElement parent )
        {
            _parent = parent;
        }

        #endregion C-Tor

        #region Public Methods

        #region Serialisation

        public XElement ToXml()
        {
            if( Tiles.Count > 0 )
            {
                XElement element = new XElement( "reserve" );

                foreach ( Tile tile in Tiles )
                {
                    element.Add( tile.ToXml() );
                }


                return element;
            }

            return null;
        }

        #endregion Serialisation

        #endregion Public Methods

        #region Event Handlers

        public void Show()
        {
            SourceControl.InteractionTray tileTray = new SourceControl.InteractionTray()
            {
                ButtonWidth = 40,
                ButtonHeight = 40,
            };

            DragDrop.Initialize( tileTray );
            tileTray.DragStop += ( Utils.DragData data, DragDropEffects mode ) =>
            {
                if ( mode == DragDropEffects.Move )
                {
                    Button button = (Button)data.DraggedObject;
                    SourceControl.ButtonInfo info = (SourceControl.ButtonInfo)button.DataContext;

                    Tiles.Remove( (Tile)info.DragData );
                }
            };

            foreach ( Tile tile in Tiles )
            {
                SourceControl.ButtonInfo info = new SourceControl.ButtonInfo()
                {
                    Canvas = tile.Canvas,
                    ToolTip = tile.Description,
                    DragData = tile,
                    IsEnabled = tile.IsEnabled
                };

                info.Click += () => { Callback?.Invoke( tile.FunctionGroup, tile.Function ); };

                tileTray.Buttons.Add( info );
            }

            tileTray.SetPositionRelativeTo( _parent, _parent.ActualWidth - tileTray.ButtonWidth, _parent.ActualHeight );

            tileTray.Show();
        }

        #endregion Event Handlers
    }
}
